<!--
 * @Author: yyyyjinying
 * @Date: 2024-07-21 22:27:52
 * @LastEditTime: 2024-07-22 00:30:47
 * @LastEditors: yyyyjinying
 * @Description: 
 * @FilePath: /zhouyi-web/src/views/dishes/materials-list.vue
 * 可以输入预定的版权声明、个性签名、空行等
-->
<template>
  <div class="flex gap-2">
    <div>
      <el-checkbox v-model="isCheckAll" :indeterminate="isIndeterminate" @change="checkAllChange">
        勾选全部规格
      </el-checkbox>
      <el-checkbox-group v-model="checkedValues" @change="checkedChange">
        <el-checkbox v-for="item in specList" :key="item.specId" :label="item.specId" :value="item.specId">
          {{ item.specName }}
        </el-checkbox>
      </el-checkbox-group>
    </div>
    <el-button type="primary" size="small" @click="addHandle" plain>新增sku</el-button>
    <table class="table-list-container">
      <thead>
        <tr>
          <th>原材料名称</th>
          <th v-for="hitem in headers" :key="hitem.id">
            {{ hitem.name }}
          </th>
          <th>数量</th>
          <th>单价</th>
          <th>单位</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item, index) in tableLists" :key="index">
          <td><el-input v-model="item.materialName"
              @change="(val: any) => inputChangeHandle(val, 'materialName', index)" /></td>

          <td v-for="(ritem, ridx) in headers" :key="ridx">
            <el-select style="width: 140px;" v-model="item[`val_${ritem.id}`]" placeholder="Select"
              @change="(val: any) => selectChange(val, index)">
              <el-option v-for="sitem in item[`list_${ritem.id}`]" :key="sitem.value_id" :label="sitem.value_name"
                :value="sitem.value_id" />
            </el-select>
          </td>
          <td><el-input v-model="item.quantity" @change="(val: any) => inputChangeHandle(val, 'quantity', index)" />
          </td>
          <td><el-input v-model="item.costPerUnit"
              @change="(val: any) => inputChangeHandle(val, 'costPerUnit', index)" /></td>
          <td><el-input v-model="item.unitOfMeasure"
              @change="(val: any) => inputChangeHandle(val, 'unitOfMeasure', index)" /></td>
          <!-- <td><el-input v-model="item.cost" @change="(val: any) => inputChangeHandle(val, 'cost', index)" /></td> -->
          <!-- <td><el-input v-model="item.image_url" /></td> -->
          <!-- <td><el-input v-model="item.status" /></td> -->
          <td><el-button type="primary" size="small" @click="deleteHandle(index, item)" plain>删除</el-button></td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script lang="ts" setup>
import { Check, Delete, Edit, Message, Search, Star } from "@element-plus/icons-vue";
import { watch, onMounted, computed, nextTick, ref } from "vue";
import { ElInput } from "element-plus";
import baseService from "@/service/baseService";

const props = defineProps({
  dishId: { type: Object, required: false },
  specType: { type: Object, required: true },
});

const emit = defineEmits(["update:materialsLists"]);

const tableLists = ref<any[]>([]);
const isCheckAll = ref(false);
const isIndeterminate = ref(true);

const checkedValues = ref<any>([]);
const specList = ref<any[]>([]);

const inputChangeHandle = (val: any, name: string, idx: number) => {
  tableLists.value = tableLists.value.map((item, index) => {
    if (index === idx) {
      item[name] = val;
    }
    return item;
  });
  emit('update:materialsLists', getRes(tableLists.value))
}

const checkAllChange = (val: boolean) => {
  checkedValues.value = val ? specList.value.map((item) => item.specId) : [];
  isIndeterminate.value = false;
  setTableLists();
};
const checkedChange = (value: string[]) => {
  const checkedCount = value.length;
  isCheckAll.value = checkedCount === specList.length;
  isIndeterminate.value = checkedCount > 0 && checkedCount < specList.length;
  setTableLists();
};

const getRes = (arrs: any[]) => {
  return arrs.map((item: any) => {
    const materialSpecification: any = {};
    Object.keys(item).forEach((key: string) => {
      if (key.includes("val_")) {
        const spec_id = key.split("_")[1];
        const value_name_id = item[key];
        if (checkedValues.value.includes(spec_id)) {
          const specName: string = specList.value.find(item => item.specId == spec_id).specName;
          const valueName: any = item[`list_${spec_id}`].find((pitem: any) => pitem.value_id === value_name_id);
          if (valueName != null) {
            materialSpecification[`${specName}`] = valueName.value_name;
          }
        }
      }
    });

    return {
      materialSpecification: JSON.stringify(materialSpecification), // json转为字符串
      dishId: item.dishId,
      configId: item.configId,
      materialName: item.materialName || null,
      quantity: item.quantity || null,
      costPerUnit: item.costPerUnit || null,
      unitOfMeasure: item.unitOfMeasure || null
    }
  });
}
const headers = computed(() => {
  return specList.value
    .filter((item) => checkedValues.value.includes(item.specId))
    .map((item) => {
      return { id: item.specId, name: item.specName };
    });
});

const setTableLists = () => {
  const record: any = { dishId: props.dishId };
  checkedValues.value.forEach((item: any) => {
    record[`field_${item}`] = item;
    record[`val_${item}`] = null;
    const specListData = specList.value.find((sitem) => sitem.specId == item);
    if (specListData != null) {
      record[`list_${item}`] = specListData.specValueStrs.split(",").map((mitem: any) => {
        const arrs = mitem.split(":")
        return { value_id: arrs[0], value_name: arrs[1] }
      })
    }
  });

  if (tableLists.value.length === 0) {
    tableLists.value = [Object.assign({ configId: null }, record)];
  } else {
    tableLists.value = tableLists.value.map((item: any) => {
      return { ...record, ...item };
    });
  }

  emit('update:materialsLists', getRes(tableLists.value))
};
const addHandle = () => {
  const record: any = { configId: null, dishId: props.dishId };
  checkedValues.value.forEach((item: any, index: number) => {
    record[`field_${item}`] = item;
    record[`val_${item}`] = null;
    const specListData = specList.value.find((sitem) => sitem.specId == item);
    if (specListData != null) {
      record[`list_${item}`] = specListData.specValueStrs.split(",").map((mitem: any) => {
        const arrs = mitem.split(":")
        return { value_id: arrs[0], value_name: arrs[1] }
      })
    }
  });

  tableLists.value.push(record);

  emit('update:materialsLists', getRes(tableLists.value))
};

const deleteHandle = (index: number, record: any) => {
  tableLists.value = tableLists.value.filter((item, idx) => index != idx);
  emit('update:materialsLists', getRes(tableLists.value))
};

const selectChange = (val: any, index: number) => {
  tableLists.value = tableLists.value.map((item, idx) => {
    if (index === idx) {
      item[`field_${val}`] = val;
    }
    return item;
  });
  emit('update:materialsLists', getRes(tableLists.value))
}



const init = (skuDataLists: any[]) => {
  specRequest(skuDataLists);
};

const specRequest = (skuDataLists: any[]) => {
  baseService
    .get("/sys/specnames/page", {
      page: 1,
      limit: 10000,
      specType: props.specType,
    })
    .then((res) => {
      if (res.code == 200) {
        specList.value = res.data.list;

        const tList: any[] = []
        const checkedValueLists: any[] = []
        skuDataLists.forEach((item: any) => {
          const record: any = { materialName: item.materialName, configId: item.configId, dishId: item.dishId, quantity: item.quantity, costPerUnit: item.costPerUnit, unitOfMeasure: item.unitOfMeasure };
          const specjson = JSON.parse(item.materialSpecification);
          specjson != null && Object.keys(specjson).forEach((specName: string, idx: number) => {
            const valueName = specjson[specName];
            specList.value.forEach((spItem: any) => {
              if (specName === spItem.specName) {
                const specId = spItem.specId;
                record[`field_${specId}`] = specId;

                const newArrs: any[] = [];
                spItem.specValueStrs.split(",").forEach((strItem: any) => {
                  const itemarrs = strItem.split(":");
                  if (valueName === itemarrs[1]) {
                    record[`val_${specId}`] = itemarrs[0];
                  }
                  newArrs.push({ value_id: itemarrs[0], value_name: itemarrs[1] });
                })
                record[`list_${specId}`] = newArrs;
                checkedValueLists.push(specId);
              }
            })
          })
          tList.push(record);
        })

        tableLists.value = tList;
        checkedValues.value = [...new Set(checkedValueLists)];
        emit('update:materialsLists', getRes(tableLists.value))
      }
    });
};
defineExpose({
  init,
});
</script>
<style lang="less" scoped>
.table-list-container {
  td {
    padding-right: 10px;
    padding-top: 5px;
    padding-bottom: 5px;
  }
}
</style>
